﻿//-----------------------------------------------------------------------
// <copyright file="WindowStyleHelper.cs" company="RelativeSet, LLC">
//
//   *** IMPORTANT - PLEASE READ ***
//
//   The MIT License (MIT)
//
//   Copyright (c) 2011 RelativeSet, LLC
//
//   Permission is hereby granted, free of charge, to any person 
//   obtaining a copy of this software and associated documentation files 
//   (the "Software"), to deal in the Software without restriction, 
//   including without limitation the rights to use, copy, modify, merge,
//   publish, distribute, sublicense, and/or sell copies of the Software,
//   and to permit persons to whom the Software is furnished to do so, 
//   subject to the following conditions:
//
//   The above copyright notice and this permission notice shall be 
//   included in all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
//   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
//   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
//   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
//   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
//   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// </copyright>
//-----------------------------------------------------------------------

namespace Glass
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Security.Principal;
    using Glass.Interop;

    /// <summary>
    /// The assembly entry-point program.
    /// </summary>
    public static class Program
    {
        #region Fields

        /// <summary>
        /// The default transparency level.
        /// </summary>
        private const byte DefaultTransparencyLevel = 200;

        /// <summary>
        /// The list of allowed process names.
        /// </summary>
        private static readonly string[] allowedProcs =
            new[] 
            {
                "cmd",
                "powershell"
            };

        /// <summary>
        /// Indicates whether or not the current process has elevated permissions.
        /// </summary>
        private static readonly Lazy<bool> hasElevatedPermissions =
            new Lazy<bool>(() => new WindowsPrincipal(WindowsIdentity.GetCurrent())
                .IsInRole(WindowsBuiltInRole.Administrator));

        #endregion // Fields

        #region Properties

        /// <summary>
        /// Gets a value indicating whether this instance has elevated permissions.
        /// </summary>
        public static bool HasElevatedPermissions
        {
            get
            {
                return Program.hasElevatedPermissions.Value;
            }
        }

        #endregion // Properties

        #region Methods

        /// <summary>
        /// The assembly entry point.
        /// </summary>
        /// <param name="args">The program arguments.</param>
        /// <returns>An integer error code value where 0 indicates successful execution.</returns>
        public static int Main(string[] args)
        {
            int result = 0 /* SUCCESS */;

            // Check permissions
            if (!Program.HasElevatedPermissions)
            {
                Console.WriteLine();
                Console.WriteLine("");
                Console.WriteLine("Info: PowerShell/Cmd processes running with elevated permissions will not be modified.");
            }

            // The default transparency level
            byte transparency = Program.DefaultTransparencyLevel;

            if (args != null /* unlikely but possible */)
            {
                // Process program arguments.
                foreach (string arg in args.Where(a => !string.IsNullOrEmpty(a)))
                {
                    // Check for the transparency flag and attempt to parse a valid value.
                    if (arg.StartsWith("-t:") || arg.StartsWith("/t:"))
                    {
                        if (!byte.TryParse(arg.Substring(3), out transparency) || transparency < 0 || transparency > 255)
                        {
                            // Warning message.
                            Console.WriteLine();
                            Console.WriteLine(
                                "Transparency must be between 0 and 255. Using default transparency value of {0}.",
                                Program.DefaultTransparencyLevel);

                            transparency = Program.DefaultTransparencyLevel;
                        }
                    }

                    // Check for 'help' flags
                    if (arg.StartsWith("-?") || arg.StartsWith("/?") || arg.StartsWith("-help") || arg.StartsWith("/help"))
                    {
                        Console.WriteLine();
                        Console.WriteLine("To specify a transparency level, use the '-t:<value>' or '/t:<value>' flag");
                        Console.WriteLine("For example; {0} /t:127", typeof(Program).Assembly.GetName().Name);

                        return result;
                    }
                }
            }

            // Get all processes that match our qualifications
            IEnumerable<Process> processes =
                Process.GetProcesses()
                    .Where(p => Program.allowedProcs.Contains(p.ProcessName));

            // Iterate through active processes
            foreach (Process process in processes)
            {
                try
                {
                    WindowStyleHelper.SetTransparency(process, transparency);
                }
                catch (Exception error)
                {
                    Console.Error.WriteLine(
                        "Failed to set window transparency (pid: {0}; reason: {1})",
                        process.Id,
                        error.Message);

                    result = 1 /* ERROR */;
                }
            }

            return result;
        }

        #endregion // Methods
    }
}